import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  message,
  Popconfirm,
  Select,
  Tree,
  Tabs,
  Row,
  Col,
  DatePicker,
  Spin,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SettingOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { roleApi, permissionApi, menuApi } from '@/services/api';

const { Option } = Select;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

interface Role {
  id: number;
  name: string;
  code: string;
  description?: string;
  status: number;
  sort: number;
  createTime: string;
}

interface Permission {
  id: number;
  code: string;
  name: string;
  type: string;
  description?: string;
}

interface Menu {
  id: number;
  name: string;
  path?: string;
  type: string;
  parentId?: number;
  children?: Menu[];
}

const Roles: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([]);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [menus, setMenus] = useState<Menu[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [checkedPermissions, setCheckedPermissions] = useState<number[]>([]);
  const [checkedMenus, setCheckedMenus] = useState<string[]>([]);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<any>({});
  const [pagination, setPagination] = useState({ 
    current: 1, 
    pageSize: 10, 
    total: 0 
  });
  
  // 权限分页相关状态
  const [permissionsPagination, setPermissionsPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
    hasMore: true
  });
  const [permissionsLoading, setPermissionsLoading] = useState(false);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<SettingOutlined />}
            onClick={() => handleSetPermissions(record)}
          >
            权限配置
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const fetchRoles = async (params = {}) => {
    setLoading(true);
    try {
      const finalParams = {
        ...params,
        page: pagination.current,
        pageSize: pagination.pageSize,
      };
      const response = await roleApi.getRoles(finalParams);
      const data = response.data || response || {};
      const roles = data.list || [];
      const total = data.total || 0;
      
      setRoles(roles);
      setPagination(prev => ({
        ...prev,
        total
      }));
    } catch (error) {
      message.error('获取角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchPermissions = async (page = 1, append = false) => {
    if (permissionsLoading) return;
    
    setPermissionsLoading(true);
    try {
      const response = await permissionApi.getPermissions({ 
        page, 
        pageSize: permissionsPagination.pageSize 
      });
      const data = response.data || response || {};
      const newPermissions = data.list || [];
      const total = data.total || 0;
      
      if (append) {
        setPermissions(prev => [...prev, ...newPermissions]);
      } else {
        setPermissions(newPermissions);
      }
      
      setPermissionsPagination(prev => ({
        ...prev,
        current: page,
        total,
        hasMore: newPermissions.length === prev.pageSize && (page * prev.pageSize) < total
      }));
    } catch (error) {
      message.error('获取权限列表失败');
    } finally {
      setPermissionsLoading(false);
    }
  };

  const loadMorePermissions = () => {
    if (permissionsPagination.hasMore && !permissionsLoading) {
      fetchPermissions(permissionsPagination.current + 1, true);
    }
  };

  const fetchMenus = async () => {
    try {
      const response = await menuApi.getMenuTree();
      const menus = response.data || response || [];
      setMenus(menus);
    } catch (error) {
      message.error('获取菜单列表失败');
    }
  };

  const handleAdd = () => {
    setEditingRole(null);
    setModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    setModalVisible(true);
    form.setFieldsValue(role);
  };

  const handleDelete = async (id: number) => {
    try {
      await roleApi.deleteRole(id);
      message.success('删除成功');
      fetchRoles(searchParams);
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingRole) {
        await roleApi.updateRole(editingRole.id, values);
        message.success('更新成功');
      } else {
        await roleApi.createRole(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchRoles(searchParams);
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    }
  };

  const handleSearch = (values: any) => {
    const params = { ...values };
    
    // 处理日期范围
    if (values.createTimeRange && values.createTimeRange.length === 2) {
      params.createTimeStart = values.createTimeRange[0].format('YYYY-MM-DD');
      params.createTimeEnd = values.createTimeRange[1].format('YYYY-MM-DD');
      delete params.createTimeRange;
    }
    
    setSearchParams(params);
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
    fetchRoles(params);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
    fetchRoles();
  };

  const handleSetPermissions = async (role: Role) => {
    setSelectedRole(role);
    setCheckedPermissions([]);
    setCheckedMenus([]);
    
    // 重置权限分页状态并获取第一页权限
    setPermissionsPagination({
      current: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    });
    setPermissions([]);
    fetchPermissions(1);
    
    setPermissionModalVisible(true);
    
    try {
      const response = await roleApi.getRoleById(role.id);
      const data = response.data || response;
      const permissionIds = data.rolePermissions?.map((rp: any) => rp.permissionId) || [];
      const menuIds = data.roleMenus?.map((rm: any) => rm.menuId.toString()) || [];
      setCheckedPermissions(permissionIds);
      setCheckedMenus(menuIds);
    } catch (error) {
      message.error('获取角色权限失败');
      setCheckedPermissions([]);
      setCheckedMenus([]);
    }
  };

  const handleSavePermissions = async () => {
    if (!selectedRole) return;

    console.log('Saving permissions for role:', selectedRole.id);
    console.log('Checked permissions:', checkedPermissions);
    console.log('Checked menus:', checkedMenus);

    try {
      await Promise.all([
        roleApi.assignPermissions(selectedRole.id, checkedPermissions),
        roleApi.assignMenus(selectedRole.id, checkedMenus.map(id => parseInt(id))),
      ]);

      message.success('权限配置成功');
      setPermissionModalVisible(false);
      fetchRoles(searchParams); // 刷新角色列表以确保数据同步
    } catch (error: any) {
      console.error('权限配置失败:', error);
      message.error(error.response?.data?.message || '权限配置失败');
    }
  };

  const buildMenuTreeData = (menus: Menu[]): any[] => {
    return menus.map(menu => ({
      key: menu.id.toString(),
      title: menu.name,
      children: menu.children ? buildMenuTreeData(menu.children) : [],
    }));
  };

  useEffect(() => {
    fetchRoles();
    fetchMenus();
  }, []);

  return (
    <div>
      {/* 查询表单 */}
      <Card title="查询条件" style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="vertical"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="keyword" label="关键词搜索">
                <Input placeholder="角色名/代码/描述" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="name" label="角色名称">
                <Input placeholder="请输入角色名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="code" label="角色代码">
                <Input placeholder="请输入角色代码" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="请选择状态" allowClear>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="createTimeRange" label="创建时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="sortBy" label="排序字段">
                <Select placeholder="请选择排序字段" allowClear>
                  <Option value="sort">排序值</Option>
                  <Option value="createTime">创建时间</Option>
                  <Option value="updateTime">更新时间</Option>
                  <Option value="name">角色名称</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="sortOrder" label="排序方向">
                <Select placeholder="请选择排序方向" allowClear>
                  <Option value="ASC">升序</Option>
                  <Option value="DESC">降序</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label=" " style={{ marginTop: 4 }}>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    查询
                  </Button>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 主表单 */}
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增角色
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={loading}
          scroll={{ y: 600 }}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              const newPagination = { current: page, pageSize: pageSize || 10, total: pagination.total };
              setPagination(newPagination);
              fetchRoles(searchParams);
            },
          }}
        />

        <Modal
          title={editingRole ? '编辑角色' : '新增角色'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          onOk={() => form.submit()}
          width={600}
        >
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              name="name"
              label="角色名称"
              rules={[{ required: true, message: '请输入角色名称' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="code"
              label="角色代码"
              rules={[{ required: true, message: '请输入角色代码' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item name="description" label="描述">
              <Input.TextArea rows={3} />
            </Form.Item>

            <Form.Item name="sort" label="排序" initialValue={0}>
              <Input type="number" />
            </Form.Item>

            <Form.Item name="status" label="状态" initialValue={1}>
              <Select>
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title={`配置角色权限：${selectedRole?.name}`}
          open={permissionModalVisible}
          onCancel={() => setPermissionModalVisible(false)}
          onOk={handleSavePermissions}
          width={800}
        >
          <Tabs defaultActiveKey="permissions">
            <TabPane tab="功能权限" key="permissions">
              <div 
                style={{ maxHeight: 400, overflow: 'auto' }}
                onScroll={(e) => {
                  const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
                  // 滚动到底部时加载更多
                  if (scrollHeight - scrollTop <= clientHeight + 5) {
                    loadMorePermissions();
                  }
                }}
              >
                {permissions.map(permission => (
                  <div key={permission.id} style={{ padding: '8px 0' }}>
                    <label>
                      <input
                        type="checkbox"
                        checked={checkedPermissions.includes(permission.id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setCheckedPermissions([...checkedPermissions, permission.id]);
                          } else {
                            setCheckedPermissions(checkedPermissions.filter(id => id !== permission.id));
                          }
                        }}
                      />
                      <span style={{ marginLeft: 8 }}>
                        {permission.name} ({permission.code})
                        <Tag color="blue" style={{ marginLeft: 8 }}>{permission.type}</Tag>
                      </span>
                    </label>
                  </div>
                ))}
                {permissionsLoading && (
                  <div style={{ textAlign: 'center', padding: '12px' }}>
                    <Spin size="small" /> 正在加载更多权限...
                  </div>
                )}
                {permissionsPagination.hasMore && !permissionsLoading && permissions.length > 0 && (
                  <div style={{ textAlign: 'center', padding: '12px' }}>
                    <Button size="small" onClick={loadMorePermissions}>
                      加载更多权限 ({permissions.length}/{permissionsPagination.total})
                    </Button>
                  </div>
                )}
                {!permissionsPagination.hasMore && permissions.length > 0 && (
                  <div style={{ textAlign: 'center', padding: '12px', color: '#999' }}>
                    已加载全部权限 (共 {permissionsPagination.total} 个)
                  </div>
                )}
              </div>
            </TabPane>
            <TabPane tab="菜单权限" key="menus">
              <Tree
                checkable
                checkedKeys={checkedMenus}
                onCheck={(checkedKeys) => setCheckedMenus(checkedKeys as string[])}
                treeData={buildMenuTreeData(menus)}
              />
            </TabPane>
          </Tabs>
        </Modal>
      </Card>
    </div>
  );
};

export default Roles;